#!/usr/bin/env python

#-*-coding: utf-8 -*-

from weibo import APIClient
import urllib
import urllib2
import httplib
import re

def get_code():
    '''get code'''
    conn = httplib.HTTPSConnection('api.weibo.com')
    params = urllib.urlencode({
    'action':'submit',
    'withOfficalFlag':'0',
    'ticket':'',
    'isLoginSina':0,
    'response_type':'code',
    'regCallback':'',
    'redirect_uri':REDIRECT_URL,
    'client_id':APP_KEY,
    'state':'',
    'from':'',
    'userId':USERID,
    'passwd':USERPASSWD,
    })
    conn.request('POST','/oauth2/authorize', params, {'Referer': url, 'Content-Type': 'application/x-www-form-urlencoded'})
    res = conn.getresponse()
    for line in res.msg.headers:
        if re.search('Location', line):
            return line.strip().split('=')[1]
    conn.close()

def get_fans(code):
    fans_list = []
    client = APIClient(app_key=APP_KEY, app_secret=APP_SECRET, redirect_uri=REDIRECT_URL)
    r = client.request_access_token(code)
    access_token = r.access_token
    expires_in = r.expires_in
    client.set_access_token(access_token, expires_in)
    next_cursor = 0
    total_fans = client.friendships.followers.get(uid=UID, cursor=next_cursor, count=10)['total_number']
    us = client.friendships.followers.get(uid=UID, cursor=next_cursor, count=total_fans)['users']
    for u in us:
        fans_list.append(u)
    return total_fans, fans_list

if __name__ == 'main':
    APP_KEY = '2099052388'
    APP_SECRET = '22dcf88d66785ccc5d01685b088e3929'
    REDIRECT_URL = 'https://api.weibo.com/oauth2/default.html'
    USERID = '13152193152'
    USERPASSWD = '020792'
    UID = '6457076817'
    url = 'https://api.weibo.com/oauth2/authorize?redirect_uri=%s&response_type=code&client_id=%s&display=default' % (urllib.quote(REDIRECT_URL), APP_KEY)
    c = get_code()
    total_fans, fans_list = get_fans(c)
    print 'number of fans: %s' % total_fans
    for fans in fans_list:
        print '%s\t%s' % (fans['id'], fans['screen_name'])